//
//  YBDevice.m
//  YBWifiAuthSDK
//
//  Created by yiban on 16/1/21.
//  Copyright © 2016年 yiban. All rights reserved.
//

#import "YBDevice.h"
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CommonCrypto/CommonDigest.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#import <mach/mach.h>

#import "YBUIDevice+Hardware.h"
#import "YBUIDevice+IdentifierAddition.h"
//#import "YBReachability.h"
#import "YBKeychainItemWrapper.h"

@implementation YBDevice

static const char* jailbreak_apps[]=
{
    "/Applications/Cydia.app",
    "/Applications/limera1n.app",
    "/Applications/greenpois0n.app",
    "/Applications/blackra1n.app",
    "/Applications/blacksn0w.app",
    "/Applications/redsn0w.app",
    NULL,
};


//是否越狱
+(BOOL)isJailBroken
{
    // Now check for known jailbreak apps. If we encounter one, the device is jailbroken.
    for(int i = 0; jailbreak_apps[i]!=NULL; ++i)
    {
        if([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithUTF8String:jailbreak_apps[i]]])
        {
            //YBLogInfo(@"isjailbroken: %s", jailbreak_apps[i]);
            return YES;
        }
    }
    // TODO: Add more checks? This is an arms-race we're bound to lose.
    return NO;
}
#define IM_DEVICE_UUID                   @"deviceUUID"

+(NSString *)UUID
{
    NSString *uuid=[[NSUserDefaults standardUserDefaults] objectForKey:IM_DEVICE_UUID];
    
    if (!uuid || uuid.length<1)
    {
        CFUUIDRef deviceId = CFUUIDCreate (NULL);
        
        CFStringRef deviceIdStringRef = CFUUIDCreateString(NULL,deviceId);
        
        CFRelease(deviceId);
        
        NSString *deviceIdString = (__bridge NSString *)deviceIdStringRef;
        
        deviceIdString = [deviceIdString stringByReplacingOccurrencesOfString:@"-" withString:@""];
        uuid=deviceIdString;
    }
    
    return uuid;
}
+ (NSString *)IMEI
{
    NSString *imei = [[UIDevice currentDevice] uniqueGlobalDeviceIdentifier];
    return imei;
}


//平台类型
+(NSString *)platform{
    
    NSString *device = [[UIDevice currentDevice].model substringToIndex:4];
    if ([device isEqualToString:@"iPho"]){
        // This is iPhone.
        return @"iphone";
    }else if ([device isEqualToString:@"iPad"]){
        // This is iPad.
        return @"iPad";
    }else if([device isEqualToString:@"iPod"]){
        // This is iPod.
        return @"iPod";
    }else{
        return @"iphone";
    }
}

//iPhone机型
+(NSString *)deviceModel{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *name = malloc(size);
    sysctlbyname("hw.machine", name, &size, NULL, 0);
    
    NSString *machine = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
    free(name);
    
    return machine;
}
//app 版本
+(NSString*)appVersion
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return version;
}
//os 版本
+(float)sysVersion
{
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    return version;
}

//OS类型
+(NSString *)mPlatform{
    
    NSString *phoneOS=[NSString stringWithFormat:@"%@%@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion]];
    phoneOS=[phoneOS stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    return phoneOS;
}

//判断屏幕  1，iphone6plus；2, iphone6, 3, iphone5, 0，iphone4，4s，touch
+ (NSInteger)boundSizeType
{
    CGRect mainFrame = [UIScreen mainScreen].bounds;
    if ([self sysVersion] < 7)
    {
        mainFrame.size.height -= 20;
    }
    
    CGSize mainSize = mainFrame.size;
    
    if (mainSize.height > 667)
    {
        return 1;
    }else if (mainSize.height > 568){
        return 2;
    }else if (mainSize.height > 480){
        return 3;
    }else{
        return 0;
    }
}


//运营商名称
+(NSString *)carrierName{
    
#if TARGET_IPHONE_SIMULATOR
    
    return @"-1";
    
#else
    
    NSString *ret=nil;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0) {
        
        CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
        CTCarrier *carrier = info.subscriberCellularProvider;
        
        //YBLogInfo(@"carrier:%@", [carrier description]);
        ret=carrier.carrierName;
    }
    
    if (!ret || ret.length==0 || [ret isEqualToString:@"Carrier"]) {
        
        ret=@"-1";
    }
    
    return ret;
    
#endif
}



//是否连接网络
+(BOOL)hasInternetConnection{
    
//    YBReachability* curReach = [YBReachability reachabilityForInternetConnection];
//    
//    YBNetworkStatus netStatus = [curReach currentReachabilityStatus];
//    
//    BOOL isReachable=NO;
//    
//    switch (netStatus)
//    {
//        case NotReachable:
//        {
//            isReachable=NO;
//            //YBLogInfo(@"InternetConnection ----------------->>>  Access Not Available");
//            break;
//        }
//            
//        case ReachableViaWWAN:
//        {
//            isReachable=YES;
//            //YBLogInfo(@"InternetConnection ----------------->>>  ReachableViaWWAN");
//            break;
//        }
//        case ReachableViaWiFi:
//        {
//            isReachable=YES;
//            //YBLogInfo(@"InternetConnection ----------------->>>  ReachableViaWiFi");
//            break;
//        }
//    }
//    
//    return isReachable;
    return YES;
}

//YBReachability* curReach;
//网络连接方式
+(NSString *)networkType{
    
    //1-3G,2-2G,3-WiFi
    
    NSString *ret=@"2g";
    
//    if (!curReach)
//    {
//        curReach = [YBReachability reachabilityForInternetConnection];
//    }
//    
//    YBNetworkStatus netStatus = [curReach currentReachabilityStatus];
//    
//    switch (netStatus)
//    {
//        case NotReachable:
//        {
//            ret=@"-1";
//            break;
//        }
//            
//        case ReachableViaWWAN:
//        {
//            ret=@"2g";
//            break;
//        }
//        case ReachableViaWiFi:
//        {
//            ret=@"wifi";
//            break;
//        }
//    }
    
    return ret;
}

// 获取当前设备可用内存(单位：MB）
+ (double)availableMemory
{
    vm_statistics_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
    kern_return_t kernReturn = host_statistics(mach_host_self(),
                                               HOST_VM_INFO,
                                               (host_info_t)&vmStats,
                                               &infoCount);
    
    if (kernReturn != KERN_SUCCESS) {
        return NSNotFound;
    }
    
    return ((vm_page_size *vmStats.free_count) / 1024.0) / 1024.0;
}


//获取可用存储空间
+(NSString *)freeDiskSpace
{
    NSDictionary *fattributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    
    float floatValue=[[fattributes objectForKey:NSFileSystemFreeSize] doubleValue]/1024.0;
    NSString *ret=[NSString stringWithFormat:@"%.0f",floatValue];
    
    return ret;
}

#pragma mark-得到当前设备是iphone还是ipad
+(UIUserInterfaceIdiom)getCurUserInterfaceIdiom
{
    return [[UIDevice currentDevice] userInterfaceIdiom];
}

#pragma mark-判断正运行的设备是否支持多任务
+(BOOL)isMutitaskingSupported
{
    if ([[UIDevice currentDevice]respondsToSelector:@selector(isMutitaskingSupported)]) {
        return [[UIDevice currentDevice]isMultitaskingSupported];
    }
    return NO;
}

#pragma mark-手电筒开关
+(void)openTorch:(AVCaptureTorchMode)AVCaptureTorchMode
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        [device setTorchMode: AVCaptureTorchMode];  // 手电筒开关
        [device unlockForConfiguration];
    }
}
+(NSString*)convertIntervalStringFromDate:(NSDate*)date
{
    NSTimeInterval interval = [date timeIntervalSince1970];
    long long int dateInterval = (long long int)interval;
    NSString *str = [NSString stringWithFormat:@"%lld",dateInterval];
    return str;
}

+ (NSString *)getSigTime {
    NSUserDefaults *userDict = [NSUserDefaults standardUserDefaults];
    NSString *username = [userDict stringForKey:@"username"];
    NSString *timeString;
    
    if ([userDict stringForKey:@"sigTimeString"]) {
        timeString = [userDict stringForKey:@"sigTimeString"];
    } else {
        timeString = [self convertIntervalStringFromDate:[NSDate date]];
        [userDict setValue:timeString forKey:@"sigTimeString"];
        [userDict synchronize];
    }
    NSString *sigString = [NSString stringWithFormat:@"%@%@",username,timeString];
    
    const char *cStr = [sigString UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, strlen(cStr), result );
    NSString *resStr = [NSString stringWithFormat:
                        @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                        result[0], result[1], result[2], result[3],
                        result[4], result[5], result[6], result[7],
                        result[8], result[9], result[10], result[11],
                        result[12], result[13], result[14], result[15]
                        ];
    resStr = [resStr substringWithRange:NSMakeRange(8, 16)];
    return resStr;
}


+ (NSString *)getUUIDString {
    YBKeychainItemWrapper *wrapper = [[YBKeychainItemWrapper alloc] initWithIdentifier:@"Account Number" accessGroup:nil];
    //从keychain里取出UUID
    NSString *uUIDString = [wrapper objectForKey:(__bridge id)kSecAttrAccount];
    
    NSString *identify;
    if (uUIDString && uUIDString.length !=0) {
        identify = uUIDString;
    } else {
        //保存数据
        NSString *uuid = [[UIDevice currentDevice].identifierForVendor UUIDString];
        [wrapper setObject:@"UUID_YIBAN" forKey:(__bridge id)kSecAttrService];
        [wrapper setObject:uuid forKey:(__bridge id)kSecAttrAccount];
        identify = uuid;
    }
    return identify;
}
//bundle 图片路径
+(NSString *)bundleImagePath:(NSString*)name type:(NSString*)type
{
    NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"YBWifiAuthBundle" ofType:@"bundle"]];
    NSString * strPath = [bundle pathForResource:name ofType:type];
    return strPath;
}

//十六进制转RGB
+ (UIColor *)colorWithHex:(NSString *)hexString
{
    if (!hexString || hexString.length==0)
    {
        return nil;
    }
    
    NSString *str=hexString;
    
    if ( ! ([hexString hasPrefix:@"0x"] || [hexString hasPrefix:@"0X"]))
    {
        str=[NSString stringWithFormat:@"0x%@",hexString];
    }
    
    int rgb;
    sscanf([str cStringUsingEncoding:NSUTF8StringEncoding], "%i", &rgb);
    UIColor *color;
    if (str.length == 10) {
        int alpha=rgb/(256*256*256)%256;
        int red=rgb/(256*256)%256;
        int green=rgb/256%256;
        int blue=rgb%256;
        
        color=[UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha/255.0];
    } else {
        int red=rgb/(256*256)%256;
        int green=rgb/256%256;
        int blue=rgb%256;
        
        color=[UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1.0];
    }
    
    
    return color;
}
+ (UIFont *)YBFoutStyle:(CGFloat)fontSize
{
    return [UIFont fontWithName:@"STHeitiSC-Light" size:fontSize];
}
@end